package com.itheima.controller;

import com.itheima.exception.MyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;

@ControllerAdvice
public class ExceptionAdvice {

    // 处理MyException类型的异常
    @ExceptionHandler(MyException.class)
    public ModelAndView doMyException(MyException ex) throws IOException {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("msg", ex.getMessage());
        modelAndView.setViewName("error.jsp");
        return modelAndView;
    }

    // 处理Exception类型的异常
    @ExceptionHandler(Exception.class)
    public ModelAndView doOtherException(Exception ex) {
        ModelAndView modelAndView = new ModelAndView();
        // 系统异常，不显示具体错误信息给用户
        modelAndView.addObject("msg", "网络异常，请稍后重试！");
        modelAndView.setViewName("error.jsp");

        // 在实际项目中，这里应该记录日志
        ex.printStackTrace();

        return modelAndView;
    }

    // 处理空指针异常
    @ExceptionHandler(NullPointerException.class)
    public ModelAndView doNullPointerException(NullPointerException ex) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("msg", "数据异常，请联系管理员。");
        modelAndView.setViewName("error.jsp");
        ex.printStackTrace();
        return modelAndView;
    }

    // 处理数组越界异常
    @ExceptionHandler(IndexOutOfBoundsException.class)
    public ModelAndView doIndexOutOfBoundsException(IndexOutOfBoundsException ex) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("msg", "数据访问越界，请检查操作。");
        modelAndView.setViewName("error.jsp");
        ex.printStackTrace();
        return modelAndView;
    }
}